package com.weixin.utils;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.weixin.pojo.message.kf.VoiceKfMessage;

/**
 * 类描述：wx转换对象为json工具<br>
 * 创建人：邓强 <br>
 * 创建时间：2017年10月27日 下午4:43:21 <br>
 * 修改人： <br>
 * 修改时间：2017年10月27日 下午4:43:21 <br>
 * 修改备注： <br>
 * 
 * @version V1.0
 */
public class WxJson {
	private static Map<SerializerFeature, Boolean> mapSerializerFeature = new HashMap<SerializerFeature, Boolean>();
	static {
		mapSerializerFeature.put(SerializerFeature.WriteMapNullValue, false); // null值不输出
	}

	public static String toJson(Object obj) {
		SerializeWriter out = null;
		try {
			out = new SerializeWriter();
			JSONSerializer serializer = new JSONSerializer(out);
			for (Map.Entry<SerializerFeature, Boolean> entrySerializerFeature : mapSerializerFeature.entrySet()) {
				serializer.config(entrySerializerFeature.getKey(), entrySerializerFeature.getValue());
			}

			serializer.write(obj);

			return out.toString();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	public static <T> T fromJson(String json, Class<T> clazz) {
		if (json == null || "".equals(json.trim())) {
			return null;
		}
		return JSON.parseObject(json, clazz);
	}

	public static void main(String[] args) {
		String s = toJson(new VoiceKfMessage("sdf"));
		System.out.println(s);
	}
}